package dk.lector;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import dk.lector.domain.ConfigFacade;

public class ConfigurationActivity extends BaseActivity {
	private String TAG = this.getClass().getSimpleName();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.config_layout);

		final EditText urlField = (EditText) findViewById(R.id.fragment_config_url);
		Button configAcceptButton = (Button) findViewById(R.id.button_fragment_config_accept);

		urlField.setText("http://pr1ze.dk/TSMobileService.svc/GetConfig");

		configAcceptButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				String param = urlField.getText().toString();
				
				registerReceiver(new BroadcastReceiver() {
				    @Override
				    public void onReceive(Context context, Intent intent) {
					unregisterReceiver(this);
					finish();
				    }
				    
				}, new IntentFilter(getString(R.string.ACTION_CONFIG_DOWNLOADED)));
				ConfigFacade.fetchConfig(ConfigurationActivity.this, param);

			}
		});

		findViewById(R.id.button_fragment_config_cancel).setOnClickListener(
				new View.OnClickListener() {

					public void onClick(View v) {
						finish();
					}
					
					
				});

		if (getIntent().getAction() != null) {
			String configURL = getIntent().getData().getQueryParameter("url");
			urlField.setText(configURL);
			// To make sure the URL doesnt persist in the intent for later.
			getIntent().setData(null);
			configAcceptButton.performClick();
		}

	}

}
